<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElSelect, ElOption, ElTag, ElTable, ElTableColumn } from 'element-plus'
import { JsonViewer } from 'vue3-json-viewer'
import 'vue3-json-viewer/dist/index.css'
import axios from 'axios'
import { AgentMapAPI } from '../../api/BackendAPI'

const azs = ref([])
const mapData = ref({})
const loading = ref(true)
// 当前选中的 AZ
const selectedAz = ref('')


// 获取部署地图数据
const fetchAgentMapData = async () => {
  try {
    loading.value = true
    // 模拟网络延迟
    const response = await axios.get(AgentMapAPI.GET_AZ_MAP)
    azs.value = response.data.data.azs
    mapData.value = response.data.data.agents
    selectedAz.value = azs.value[0]
  } catch (error) {
    console.error('获取地图数据失败:', error)
    // 可以添加错误提示
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAgentMapData()
})

// 将数据转换为表格格式
const tableData = computed(() => {
  const currentAzData = mapData.value[selectedAz.value] || {}
  const data = Object.entries(currentAzData).map(([hostname, agents]) => ({
    hostname,
    agents
  }))
  
  data.sort((item1, item2) => {
    return item1.hostname.localeCompare(item2.hostname);
  });
  return data
})

// 根据状态获取标签类型
const getTagType = (status) => {
  return status === 'health' ? 'success' : 'warning'
}

// 添加抽屉相关的状态
const drawerVisible = ref(false)
const detailData = ref(null)

// 获取agent详细数据
const fetchAgentDetailData = async (hostname, agent, role) => {
  try {
    // 模拟网络延迟
    const encodedHostname = encodeURIComponent(hostname)
    const encodedAgent = encodeURIComponent(agent)
    const encodedRole = encodeURIComponent(role)

    const response = await axios.get(`${AgentMapAPI.GET_AGENT_INFO}?hostname=${encodedHostname}&agent=${encodedAgent}&role=${encodedRole}`)
    detailData.value = response.data.data
  } catch (error) {
    console.error('获取详情数据失败:', error)
    // 可以添加错误提示
  } finally {
  }
}

// 修改点击事件处理函数
const handleTagClick = (item) => {
  drawerVisible.value = true
  fetchAgentDetailData(item.hostname, item.agent, item.role)
}

</script>

<template>

  <el-card class="box-card" shadow="never" style="margin:10px;">
    <!-- AZ 选择下拉框 -->
    <div class="select-container">
      <span class="label">逻辑机房: </span>
      <el-select 
        v-model="selectedAz" 
        placeholder="请选择机房" 
        style="width: 200px;"
        filterable
      >
      <el-option
        v-for="az in azs"
        :key="az"
        :label="az"
        :value="az"
      />
      </el-select>
    </div>

    <!-- 展示表格 -->
    <el-table 
      :data="tableData" 
      style="width: 100%; margin-top: 20px"
      resizable
      border
    >
      <el-table-column prop="hostname" label="主机名" width="300" />
      <el-table-column label="产品 [角色]">
        <template #default="scope">
          <div class="tags-container">
            <el-tag
              v-for="agent in scope.row.agents"
              :key="agent.agent + '-' + agent.role"
              :type="getTagType(agent.status)"
              @click="handleTagClick(agent)"
              class="agent-tag"
            >
              {{ agent.agent + ' [' + agent.role + ']' }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 添加抽屉组件 -->
  <el-drawer
    v-model="drawerVisible"
    title="详细信息"
    direction="rtl"
    size="30%"
  >
    <json-viewer
      v-if="detailData"
      :value="detailData"
      :expand-depth="2"
      copyable
      boxed
    />
   
  </el-drawer>

</template>

<style scoped>
.container {
  padding: 20px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.agent-tag {
  cursor: pointer;
}

:deep(.el-table th) {
  font-weight: bold;
  background-color: #f2f2f2; /* 浅灰色 */
  color: #333; /* 深灰色 */
}

:deep(.el-table) {
  border: 1px solid #dcdfe6;
}

:deep(.el-table td),
:deep(.el-table th) {
  border: 1px solid #dcdfe6;
}

:deep(.el-select-dropdown__item) {
  font-weight: normal !important;
}
</style>